﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Xamarin.Essentials;


using Accouting804.Models.Orm;
using System.IO;
using System.Reflection;
using SQLitePCL;
using Accouting804.Setting;
using Plugin.FilePicker;
using Plugin.FilePicker.Abstractions;

namespace Accouting804.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class AdminPage : ContentPage
    {

        public const string DatabaseFilename = "db.db3";
        public static string DatabasePath
        {
            get
            {
                var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                return Path.Combine(basePath, DatabaseFilename);
            }
        }
        public AdminPage()
        {
            InitializeComponent();



        }

        private void Button_Clicked(object sender, EventArgs e)
        {

            this.initdb_btn_Clicked(sender, e);
        }


        private void initdb_btn_Clicked(object sender, EventArgs e)
        {
            try
            {
                InitializeSetting.InitDb();
            }
            catch (Exception ex)
            {
                DisplayAlert("Exception", ex.Message, "Ok");
            }
        }

        private void checkdb_btn_Clicked(object sender, EventArgs e)
        {
            var result = InitializeSetting.SettingDBExist();
            DisplayAlert("info", result.ToString(), "ok");
        }


        private void checkaccdb_btn_Clicked(object sender, EventArgs e)
        {
            var result = InitializeSetting.AccountDBExistAndComplete();
            DisplayAlert("info", result.ToString(), "ok");
        }

        private void Share_Clicked(object sender, EventArgs e)
        {
            var fn = "Attachment.txt";
            var file = Path.Combine(FileSystem.CacheDirectory, fn);
            File.WriteAllText(file, "Hello World");

            var fullpath = file;
            var contentType = "text/plain";
            try
            {

                var sf = new ShareFile(fullpath, contentType);
                var shareFile = new ShareFileRequest()
                {
                    Title = "db",
                    //File = new ShareFile(InitializeSetting.SettingDBPath, "application/octet-stream")
                    File = sf
                };
                Share.RequestAsync(shareFile); ;
            }
            catch (Exception ex)
            {
                DisplayAlert("Exception", $"{fullpath} 共享失败", "Ok");
            }


            //Task taskShare = Share.RequestAsync("share text", "share tile");

        }

        private async Task location_btn_ClickedAsync(object sender, EventArgs e)
        {

            Action action = async () =>
            {

                var request = new GeolocationRequest(GeolocationAccuracy.High);
                var location = await Geolocation.GetLocationAsync(request);

                if (location != null)
                {
                    await DisplayAlert("Info", $"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}", "Ok");
                }
            };



            try
            {
                action.Invoke();
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {





                // Handle permission exception
            }
            catch (Exception ex)
            {
                // Unable to get location
            }
        }

        private void location_btn_Clicked(object sender, EventArgs e)
        {
            this.location_btn_ClickedAsync(sender, e);
        }

        private void battery_btn_Clicked(object sender, EventArgs ee)
        {

            Battery.BatteryInfoChanged += (sernder, e) =>
            {

                var level = e.ChargeLevel;
                var state = e.State;
                var source = e.PowerSource;

                var str = $"Reading: Level: {level}, State: {state}, Source: {source}\n";

                this.loglab.Text += str;


            };


        }

        private async void map_btn_Clicked(object sender, EventArgs e)
        {
            var location = new Location(39.91, 116.3906032);
            var options = new MapLaunchOptions { NavigationMode = NavigationMode.Driving };
            try
            {
                //Map.OpenAsync(location, options);
                await Map.OpenAsync(location, new MapLaunchOptions()
                {

                    Name = "中国梦"
                });



            }

            catch (Exception ex)
            {
                await DisplayAlert("Exception", ex.Message, "Ok");
                throw;
            }
            finally
            {
                try
                {


                }
                catch (Exception)
                {

                    throw;
                }

            }

        }

        private void ldf_btn_Clicked(object sender, EventArgs e)
        {
            Action action = async () =>
            {
                try
                {
                    FileData fileData = await CrossFilePicker.Current.PickFile();
                    if (fileData == null)
                        return; // user canceled file picking

                    string fileName = fileData.FileName;
                    string contents = System.Text.Encoding.UTF8.GetString(fileData.DataArray);

                    DisplayAlert("Info", fileData.DataArray.Length.ToString(), "Ok");
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("Exception choosing file: " + ex.ToString());
                }
            };

            action.Invoke();


        }

        private void exportacc_btn_Clicked(object sender, EventArgs e)
        {
            var accPath = InitializeSetting.AccountRecordsDbPath;
            var file = accPath;
            var fullpath = file;

            try
            {


                var shareFile = new ShareFileRequest()
                {
                    Title = "db",
                    File = new ShareFile(fullpath, "application/octet-stream")
                };
                Share.RequestAsync(shareFile); ;
            }
            catch (Exception ex)
            {
                DisplayAlert("Exception", $"{fullpath} 共享失败", "Ok");
            }

        }

        private async void delete_btn_Clicked(object sender, EventArgs e)
        {
            var result = await DisplayActionSheet("Warn", "Cancel", "Destruction", new string[]
            {
                "Delete"
            }
            );


            if (result.ToUpper()== "DELETE".ToUpper())
            {

                InitializeSetting.DelelteAllDb();
                //DisplayAlert("Info", $"{result} Clicked", "Ok");
            }
        }
    }
}